package cn.edu.buu.hospital.web;
import cn.edu.buu.hospital.entity.Report;
import cn.edu.buu.hospital.entity.User;
import cn.edu.buu.hospital.service.ReportService;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;

@Controller
@RequestMapping("/report")
public class ReportController {
    @Autowired
    private ReportService reportService;
    
    // 查询报告列表
    @RequestMapping(value = "/find", method = {RequestMethod.GET, RequestMethod.POST})
    public String find(Model model,
                      @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                      Report condition,
                      HttpSession session) {
        int pageSize = 5;
        // 从session中获取当前登录用户信息
        User loginUser = (User) session.getAttribute("loginAdmin");
        // 如果是病人用户(type=1)，则只能查看自己的病单报告
        if (loginUser != null && loginUser.getType() == 1) {
            // 使用findByUserId方法查询用户的报告
            PageInfo<Report> pageInfo = reportService.findByUserId(pageNum, pageSize, loginUser.getUserid());
            model.addAttribute("pageInfo", pageInfo);
            model.addAttribute("patientName", loginUser.getUsername());
            return "backend/report/list";
        }
        // 非病人用户可以按条件搜索
        PageInfo<Report> pageInfo = reportService.find(pageNum, pageSize, condition);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("condition", condition);
        return "backend/report/list";
    }
    
    // 根据ID查询病单报告（用于查看详情）
    @GetMapping("/findById")
    public String findById(@RequestParam("reportId") Long reportId, Model model) {
        // 根据ID查询病单报告信息
        Report report = reportService.findById(reportId);
        if (report == null) {
            report = new Report();
            // 设置ID，用于页面显示
            report.setReportid(reportId);
        }
        model.addAttribute("report", report);
        return "backend/report/detail";
    }
    
    // 更新病单报告
    @PostMapping("/update")
    public String update (Report report, Model model, HttpSession session){
        // 权限检查：只有非病人用户(type!=1)可以更新病单报告
        User loginUser = (User) session.getAttribute("loginAdmin");
        if (loginUser != null) {
            if (loginUser.getType() == 1) {
                model.addAttribute("error", "病人用户不能修改病单报告");
                model.addAttribute("report", report);
                return "backend/report/detail";
            }
        }
        
        try {
            // 当管理员提交医生建议时，自动更新生成时间
            if (report.getDoctoradvice() != null && !report.getDoctoradvice().equals("待医生诊断后更新")) {
                report.setCreatetime(LocalDateTime.now());
                report.setCreateTime(LocalDateTime.now().toString());
            }
            
            reportService.modify(report);
            // 更新成功后重定向到详情页
            return "redirect:findById?reportId=" + report.getReportid();
        } catch (Exception e) {
            model.addAttribute("error", "更新失败: " + e.getMessage());
            model.addAttribute("report", report);
            return "backend/report/detail";
        }
    }
    
    /*
     * 以下添加病单报告的功能已被禁用
     */// 跳转到添加病单报告页面
    /*@GetMapping("/toAdd")
    public String toAdd(Model model, HttpSession session) {
        // 权限检查：只有非病人用户(type!=1)可以添加病单报告
        User loginUser = (User) session.getAttribute("loginAdmin");
        if (loginUser != null) {
            if (loginUser.getType() == 1) {
                model.addAttribute("error", "病人用户不能添加病单报告");
                return "redirect:find";
            }
        }
        
        model.addAttribute("report", new Report());
        return "backend/report/add";
    }
    
    // 添加病单报告
    @PostMapping("/add")
    public String add(Report report, Model model, HttpSession session) {
        // 权限检查：只有非病人用户(type!=1)可以添加病单报告
        User loginUser = (User) session.getAttribute("loginAdmin");
        if (loginUser != null) {
            if (loginUser.getType() == 1) {
                model.addAttribute("error", "病人用户不能添加病单报告");
                model.addAttribute("report", report);
                return "backend/report/add";
            }
        }
        
        try {
            // 检查该预约ID是否已有报告
            if (report.getAppointmentid() != null) {
                Report condition = new Report();
                condition.setAppointmentid(report.getAppointmentid());
                PageInfo<Report> existingReports = reportService.find(1, 1, condition);
                if (existingReports != null && existingReports.getList() != null && !existingReports.getList().isEmpty()) {
                    model.addAttribute("error", "该预约记录已存在报告，不能重复添加");
                    model.addAttribute("report", report);
                    return "backend/report/add";
                }
            }
            
            // 设置创建时间
            LocalDateTime now = LocalDateTime.now();
            report.setCreatetime(now);
            report.setCreateTime(now.toString()); // 同时设置字符串格式的时间
            reportService.add(report);
            return "redirect:find";
        } catch (Exception e) {
            model.addAttribute("error", "添加失败: " + e.getMessage());
            model.addAttribute("report", report);
            return "backend/report/add";
        }
    }*/
    
    // 删除病单报告
    @GetMapping("/delete")
    public String delete(@RequestParam("reportId") Long reportId, HttpSession session, Model model) {
        // 权限检查：只有非病人用户(type!=1)可以删除病单报告
        User loginUser = (User) session.getAttribute("loginAdmin");
        if (loginUser != null) {
            if (loginUser.getType() == 1) {
                // 对于病人用户，添加错误消息并重定向到列表页
                model.addAttribute("error", "病人用户不能删除病单报告");
                // 由于是重定向，需要将错误消息存放到session中
                session.setAttribute("error", "病人用户不能删除病单报告");
                return "redirect:find";
            }
        }
        
        try {
            reportService.removeById(reportId);
        } catch (Exception e) {
            // 忽略删除失败的异常，继续重定向到列表页
        }
        return "redirect:find";
    }
}